package com.example.dwr.gidemo.bus;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.directwebremoting.Browser;
import org.directwebremoting.Hub;
import org.directwebremoting.HubFactory;

public class Simulator
  implements Runnable
{
  private final Random random = new Random();
  private int attributesPerRecord = 5;
  private int publishesPerSecond = 1;
  private boolean active = false;
  private final Map<String, Map<String, String>> objectHolder = new HashMap();
  private static final Log log = LogFactory.getLog(Simulator.class);

  public Simulator()
  {
    setActive(true);
  }

  public void run()
  {
    try
    {
      log.info("Simulator: Starting server-side thread");

      while (this.active)
      {
        Browser.withPage("/dwr-gi/dwr_oa_gi.html", new Runnable()
        {
          public void run()
          {
        	  //objectHolder.put("obj", Simulator.access$000(this.this$0));
            HubFactory.get().publish("cdf.object", this);
          }

        });
        Thread.sleep(this.random.nextInt(500));
      }

      log.info("Simulator: Stopping server-side thread");
    }
    catch (InterruptedException ex)
    {
      ex.printStackTrace();
    }
  }

  private Map<String, String> getRandomObject()
  {
    Map reply = new HashMap();

    reply.put("jsxid", "" + this.random.nextInt(10));

    for (int i = 1; i <= this.attributesPerRecord; ++i)
    {
      reply.put("C" + i, getRandomNumberString());
    }

    return reply;
  }

  private String getRandomNumberString()
  {
    float base = this.random.nextInt(100000);
    base /= 100.0F;
    return String.valueOf(base);
  }

  public int getAttributesPerRecord()
  {
    return this.attributesPerRecord;
  }

  public void setAttributesPerRecord(int attributesPreRecord)
  {
    this.attributesPerRecord = attributesPreRecord;
  }

  public int getPublishesPerSecond()
  {
    return this.publishesPerSecond;
  }

  public void setPublishesPerSecond(int publishesPerSecond)
  {
    this.publishesPerSecond = publishesPerSecond;
  }

  public synchronized void setActive(boolean active)
  {
    if (active == this.active)
    {
      return;
    }

    this.active = active;
    log.warn("Simulator: Setting active state to: " + active);

    if (this.active)
    {
      new Thread(this).start();
    }
  }

  public boolean isActive()
  {
    return this.active;
  }
}